package org.chw.netty.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @ClassName: EchoServerHandler
 * @Description: 处理入站事件
 * @Autor: Vincent.Chen
 * @Create: 2018/6/8 14:44
 * @Version: 1.0
 **/
@ChannelHandler.Sharable
public class EchoServerHandler extends ChannelInboundHandlerAdapter {
    private static final Logger LOGGER = LoggerFactory.getLogger(EchoServerHandler.class);

    /**
     * @return void
     * @Author: Vincent.Chen
     * @Description: 每个信息入站时调用
     * @Date 2018/6/8 14:46
     * @Param [ctx, msg]
     **/
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        ByteBuf in = (ByteBuf) msg;
        LOGGER.info("Server received:{}", in.toString(CharsetUtil.UTF_8));
        ctx.write(in); //将消息返回给发送者，此时数据还没有刷新
    }

    /**
     * @return void
     * @Author: Vincent.Chen
     * @Description: 通知处理器最后的 channelread() 是当前批处理中的最后一条消息时调用
     * @Date 2018/6/8 14:47
     * @Param [ctx]
     **/
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        //冲刷所有待审消息到远程节点。关闭通道后，操作完成
        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
    }

    /**
     * @return void
     * @Author: Vincent.Chen
     * @Description: 读操作时捕获到异常时调用
     * @Date 2018/6/8 14:48
     * @Param [ctx, cause]
     **/
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        LOGGER.error("ERROR:", cause);    //打印异常堆栈
        ctx.close();    //关闭通道
    }
}
